import axios from 'axios';
import {
    Message
} from 'element-ui';
import store from '../store'
import sha1 from 'js-sha1'

axios.defaults.timeout = 30000;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';
axios.defaults.headers.delete['Content-Type'] = 'application/json';

// axios.defaults.headers.post['Authorization'] = "bearer;" + store.state.d_a;

export default {
    ajax(obj = {}) {
        if (obj.code) {
            axios.defaults.baseURL = '/' + obj.code + '/';
        } else {
            axios.defaults.baseURL = '/htk-admin/';
        }
        obj.data = !obj.data ? {} : obj.data;
        if (!obj.data.crteAdminId) {
            obj.data.crteAdminId = store.state.admin.id;
            obj.data.crteMngId = store.state.admin.id;
        }
        if (!obj.data.orgId) {
            obj.data.orgId = store.state.admin.orgId;
        }
        obj.data.updtAdminId = store.state.admin.id;
        obj.data.updtMngId = store.state.admin.id;

        let time = Date.parse(new Date()) / 1000;
        let userToken = store.state.admin.userToken;
        let sign = "";
        if (userToken) {
            let tokenKeys = userToken.split("_");
            sign = sha1(tokenKeys[0] + time + tokenKeys[1])
        }

        axios({
            method: !obj.method ? 'post' : obj.method,
            url: obj.url,
            responseType: !obj.resType ? 'json' : obj.resType,
            data: JSON.stringify(obj.data),
            headers: {
                time: Date.parse(new Date()) / 1000,
                sign: sign,
                userKey: store.state.admin.id
            }
        }).then((res) => {
            if (obj.resType && obj.resType == 'arraybuffer') {
                obj.success && obj.success(res.data);
            } else {
                if (res.data.code !== 0) {
                    Message.warning(res.data.msg);
                    obj.fail && obj.fail(res.data);
                    return;
                }
                obj.success && obj.success(res.data.data);
            }
        }).catch((error) => {
            console.log(error);
            obj.error && obj.error(error);
        });
    }
}